package com.ssy.lingxi.enhance.serviceimpl.process;

import com.querydsl.core.BooleanBuilder;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.enhance.constant.*;
import com.ssy.lingxi.enhance.entity.InnerWorkflowRecordDO;
import com.ssy.lingxi.enhance.entity.ProduceNoticeOrderDO;
import com.ssy.lingxi.enhance.entity.QProduceNoticeOrderDO;
import com.ssy.lingxi.enhance.handler.async.MessageAsyncService;
import com.ssy.lingxi.enhance.handler.async.ReportAsyncService;
import com.ssy.lingxi.enhance.handler.jpa.QueryDslUtil;
import com.ssy.lingxi.enhance.model.dto.ExamDTO;
import com.ssy.lingxi.enhance.model.qo.ProduceNoticeOrderQO;
import com.ssy.lingxi.enhance.model.vo.ProduceNoticeOrderListVO;
import com.ssy.lingxi.enhance.repository.InnerWorkflowRecordRepository;
import com.ssy.lingxi.enhance.repository.ProduceNoticeOrderRepository;
import com.ssy.lingxi.enhance.service.process.ProcessToBeSubmitExamService;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.report.api.enums.EnhanceProcessOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 加工能力 - 确认生产通知单(加工企业) - 待提交审核生产通知单 - 业务实现层
 * @author fhj
 * @date 2020/10/20
 * @version 2.0.0
 */
@Slf4j
@Service
public class ProcessToBeSubmitExamServiceImpl implements ProcessToBeSubmitExamService {

    @Resource
    private ProcessFeign processFeign;
    @Resource
    private QueryDslUtil queryDslUtil;
    @Resource
    private ProduceNoticeOrderRepository produceNoticeOrderRepository;
    @Resource
    private InnerWorkflowRecordRepository innerWorkflowRecordRepository;
    @Resource
    private ReportAsyncService reportAsyncService;
    @Resource
    private MessageAsyncService messageAsyncService;

    /**
     * 列表
     * */
    @Override
    public Wrapper<PageData<ProduceNoticeOrderListVO>> list(ProduceNoticeOrderQO qo, UserLoginCacheDTO user) {
        //查询表实体 - 生产通知单
        QProduceNoticeOrderDO pno = QProduceNoticeOrderDO.produceNoticeOrderDO;

        //查询条件构造 - 必要条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(pno.processMemberId.eq(user.getMemberId()));
        predicates.and(pno.processRoleId.eq(user.getMemberRoleId()));
        predicates.and(pno.outerStatus.eq(PNOOuterStatusEnum.TO_BE_CONFIRM.getCode()));
        predicates.and(pno.processInnerStatus.eq(PNOProcessInnerStatusEnum.TO_BE_SUBMIT_EXAM.getCode()));

        return Wrapper.success(queryDslUtil.getProcessPNOList(qo, pno, predicates));
    }

    /**
     * 审核
     * */
    @Override
    @Transactional
    public Wrapper<Void> exam(ExamDTO dto, UserLoginCacheDTO user) {
        //如果审核不通过时, 校验审核不通过原因是否为空
        if(dto.getStatus().equals(ExamStatusEnum.NO.getCode()) && StringUtils.isBlank(dto.getCause())) {
            return Wrapper.fail(ResponseCode.ENHANCE_VALIDATE_DISAGREE_REASON_CAN_NOT_BE_EMPTY);
        }

        //根据ID获取生产通知单详情
        ProduceNoticeOrderDO produceNoticeOrder = produceNoticeOrderRepository.findById(dto.getId()).orElse(null);
        if(produceNoticeOrder == null) {
            return Wrapper.fail(ResponseCode.ENHANCE_BY_ID_NOT_FOUND_PNO);
        }
        if(!produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.TO_BE_PROCESS_SUBMIT_EXAM.getCode())) {
            return Wrapper.fail(ResponseCode.ENHANCE_ONLY_SUBMIT_INNER_STATUS_AS_TO_BE_PROCESS_SUBMIT_EXAM);
        }
        if(dto.getDeliveryMessage() == null
                || dto.getDeliveryMessage().getDeliveryAddressId() == null
                || StringUtils.isBlank(dto.getDeliveryMessage().getDeliveryAddress())
                || StringUtils.isBlank(dto.getDeliveryMessage().getDeliveryUserName())
                || StringUtils.isBlank(dto.getDeliveryMessage().getDeliveryUserTel())) {
            return Wrapper.fail(ResponseCode.ENHANCE_DELIVERY_MESSAGE_NOT_NULL);
        }

        //调用工作流服务 -> 执行加工企业内部流程
        TaskExecuteVO taskExecuteVO = new TaskExecuteVO();
        taskExecuteVO.setMemberId(produceNoticeOrder.getProcessMemberId());
        taskExecuteVO.setRoleId(produceNoticeOrder.getProcessRoleId());
        taskExecuteVO.setDataId(produceNoticeOrder.getId());
        taskExecuteVO.setTaskId(produceNoticeOrder.getProcessInnerTaskId());
        taskExecuteVO.setAgree(dto.getStatus());
        taskExecuteVO.setProcessKey(produceNoticeOrder.getProcessInnerProcessKey());
        Wrapper<SimpleTaskCompleteVO> wrapper = processFeign.completeSimpleTask(taskExecuteVO);
        if(ResponseCode.SUCCESS.getCode() == wrapper.getCode()) {
            //记录加工企业内部工作流记录
            InnerWorkflowRecordDO innerWorkflowRecord = new InnerWorkflowRecordDO();
            innerWorkflowRecord.setProduceNoticeOrderId(produceNoticeOrder.getId());
            innerWorkflowRecord.setUserId(user.getUserId());
            innerWorkflowRecord.setMemberId(user.getMemberId());
            innerWorkflowRecord.setRoleId(user.getMemberRoleId());
            innerWorkflowRecord.setType(RoleTypeEnum.PROCESS.getCode());
            innerWorkflowRecord.setStep(produceNoticeOrder.getProcessInnerStatus());
            innerWorkflowRecord.setOperator(user.getUserName());
            innerWorkflowRecord.setDepartment(user.getUserOrgName());
            innerWorkflowRecord.setJobTitle(user.getUserJobTitle());
            innerWorkflowRecord.setStatus(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? "待审核(一级)" : "提交审核不通过");
            innerWorkflowRecord.setOperate("提交审核生产通知单");
            innerWorkflowRecord.setOperateTime(System.currentTimeMillis());
            innerWorkflowRecord.setOpinion(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? "同意" : "不同意");
            innerWorkflowRecordRepository.saveAndFlush(innerWorkflowRecord);

            //更新发货地址ID, 发货地址、发货人、发货人电话、状态、加工企业内部状态、加工企业内部任务ID
            produceNoticeOrder.setDeliveryAddressId(dto.getDeliveryMessage().getDeliveryAddressId());
            produceNoticeOrder.setDeliveryAddress(dto.getDeliveryMessage().getDeliveryAddress());
            produceNoticeOrder.setDeliveryUserName(dto.getDeliveryMessage().getDeliveryUserName());
            produceNoticeOrder.setDeliveryUserTel(dto.getDeliveryMessage().getDeliveryUserTel());
            produceNoticeOrder.setStatus(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? PNOAllStatusEnum.TO_BE_PROCESS_EXAM1.getCode() : PNOAllStatusEnum.PROCESS_SUBMIT_NOT_PASSED.getCode());
            produceNoticeOrder.setProcessInnerStatus(wrapper.getData().getStatus());
            produceNoticeOrder.setProcessInnerTaskId(wrapper.getData().getTaskId());
            produceNoticeOrder.setCause(dto.getCause());
            produceNoticeOrderRepository.saveAndFlush(produceNoticeOrder);
        }else {
            log.error("工作流服务异常:" + wrapper.getMessage());
            throw new BusinessException(ResponseCode.ENHANCE_WORKFLOW_ERROR);
        }

        //调用报表服务、消息服务 -> 新增操作通知、发送系统消息（如果调用过程出现异常, 无需回滚, 直接catch打印日志正常返回。）
        if(dto.getStatus().equals(ExamStatusEnum.YES.getCode())) {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_PROCESS.getCode(),
                    EnhanceProcessOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(),  1L,
                    EnhanceProcessOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L
            );
            messageAsyncService.sendSystemMessage(produceNoticeOrder.getProcessMemberId(), produceNoticeOrder.getProcessRoleId(),
                    MessageTemplateCode.production_order_handle_audit_step_1, Stream.of(produceNoticeOrder.getNoticeNo(), produceNoticeOrder.getSummary()).collect(Collectors.toList())
            );
        }else {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_PROCESS.getCode(),
                    EnhanceProcessOperateTypeEnum.TO_BE_CONFIRM.getCode(),  1L,
                    EnhanceProcessOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L
            );
            messageAsyncService.sendSystemMessage(produceNoticeOrder.getProcessMemberId(), produceNoticeOrder.getProcessRoleId(),
                    MessageTemplateCode.production_order_handle_confirm, Stream.of(produceNoticeOrder.getNoticeNo(), produceNoticeOrder.getSummary()).collect(Collectors.toList())
            );
        }

        return Wrapper.success();
    }
}
